package com.ebt.m.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.account.json.ValidateCodeSendResponse;
import com.ebt.m.account.ui.ActForgetPwdGetAccount;
import com.ebt.m.homepage.ActionItemView;
import com.ebt.m.commons.buscomponent.thirtylogin.ShareConstants;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ILoginManager;
import com.ebt.m.commons.buscomponent.thirtylogin.model.PlatformActionListener;
import com.ebt.m.commons.buscomponent.thirtylogin.qq.QQLoginManager;
import com.ebt.m.commons.buscomponent.thirtylogin.wechat.WechatLoginManager;
import com.ebt.m.commons.buscomponent.thirtylogin.weibo.WeiboLoginManger;
import com.ebt.m.presenter.LoginContract;
import com.ebt.m.presenter.LoginPresenter;
import com.ebt.m.proposal_v2.widget.dialog.EBTProgressDialog;
import com.ebt.m.utils.InputCheckUtil;
import com.ebt.m.utils.KeyboardChangeListener;
import com.ebt.m.utils.StateManager;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.jakewharton.rxbinding2.view.RxView;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.connect.common.Constants;
import com.tendcloud.tenddata.TCAgent;


import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by andy
 */
public class LoginActivity extends BaseToolBarActivity implements RadioGroup.OnCheckedChangeListener, LoginContract.IView, KeyboardChangeListener.KeyBoardListener {


    @BindView(R.id.container)
    LinearLayout content;
    @BindView(R.id.rd_login_phone)
    RadioButton mRdLoginPhone;
    @BindView(R.id.rd_login_pwd)
    RadioButton mRdLoginPwd;
    @BindView(R.id.rd_group)
    RadioGroup mRdGroup;
    @BindView(R.id.login_phone_container)
    View mPhoneContainer;
    @BindView(R.id.login_pwd_container)
    View mPwdContainer;
    @BindView(R.id.login_username)
    EditText loginUsername;
    @BindView(R.id.login_password)
    EditText loginPassword;
    @BindView(R.id.action_forget_pwd)
    Button mActionForgetPwd;
    @BindView(R.id.login_button)
    Button loginButton;
    @BindView(R.id.action_wechat)
    ActionItemView actionWechat;
    @BindView(R.id.action_weibo)
    ActionItemView actionWeibo;
    @BindView(R.id.action_qq)
    ActionItemView actionQq;
    @BindView(R.id.login_phone)
    EditText mLoginPhone;
    @BindView(R.id.action_getcode)
    Button mActionGetcode;
    @BindView(R.id.login_code)
    EditText mLoginCode;
    @BindView(R.id.login_button_phone)
    Button mLoginButtonPhone;
    @BindView(R.id.cb_show_pwd)
    CheckBox mCbShowPwd;
    private QQLoginManager qqLoginManager;
    private EBTProgressDialog mProgressDialog;
    private SsoHandler mSsoHandler;
    private LoginPresenter mPresenter;
    private ValidateCodeSendResponse mVerificationCodeResult;
    private KeyboardChangeListener mKeyboardChangeListener;

    public static final String ACTION_FROM_RESETPWD = "ACTION_FROM_RESETPWD";
    public static final String ACTION_FROM_CREATE = "ACTION_FROM_CREATE";

    public static final String USERNAME_KEY = "username";
    public static final String PASSWORD_KEY = "password";

    private boolean isShow = false;
    private float translateDelta;

    private TimerCounter mInitTimerCounter;
    private TimerCounter mNormalTimerCounter;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
        initData();
        mPresenter = new LoginPresenter(this, this);
        initProgressDialog();
        content.post(new Runnable() {
            @Override
            public void run() {
                mKeyboardChangeListener = new KeyboardChangeListener(content, toolbar.getHeight());
                mKeyboardChangeListener.setKeyBoardListener(LoginActivity.this);
            }
        });
        initAnimation();
        initValidateCodeStatus();
    }

    private void initValidateCodeStatus() {
        long lastValidateCodeTime = StateManager.getInstance(this).getLong(StateManager.LOGIN_VALIDATECODE_TIME);
        long deltaTime = System.currentTimeMillis() - lastValidateCodeTime;
        if (deltaTime < 60 * 1000 && deltaTime > 0) {
            mInitTimerCounter = new TimerCounter(60 * 1000 - deltaTime, 1000);
            mInitTimerCounter.start();
        }
    }

    private void initAnimation() {
        translateDelta = getResources().getDimension(R.dimen.login_logo_container);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        initData();
    }

    private void initData() {
        mRdGroup.setOnCheckedChangeListener(this);
        Intent intent = getIntent();
        String action = intent.getAction();
        if (ACTION_FROM_RESETPWD.equals(action) || ACTION_FROM_CREATE.equals(action)) {
            initAction(intent);
            mRdLoginPwd.setChecked(true);
            switchContent(1);
        } else {
            mRdLoginPhone.setChecked(true);
            switchContent(0);
        }
        initLoginBtState();
        mCbShowPwd.setChecked(false);
        mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int inputType = loginPassword.getInputType();
                if (inputType != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    loginPassword
                            .setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    loginPassword.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                String pwd = loginPassword.getText().toString().trim();
                if (!TextUtils.isEmpty(pwd)) {
                    loginPassword.setSelection(pwd.length());
                }
            }
        });
        RxView.clicks(mActionGetcode)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    actionGetCode();
                });
    }

    private void initAction(Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle.containsKey(USERNAME_KEY))
            loginUsername.setText(bundle.getString(USERNAME_KEY));
        if (bundle.containsKey(PASSWORD_KEY))
            loginPassword.setText(bundle.getString(PASSWORD_KEY));
    }

    private void initLoginBtState() {
        changeLoginState();
        EditTextListner textListner = new EditTextListner();
        mLoginPhone.addTextChangedListener(textListner);
        mLoginCode.addTextChangedListener(textListner);
        loginUsername.addTextChangedListener(textListner);
        loginPassword.addTextChangedListener(textListner);
    }

    private void changeLoginState() {
        String loginPhone = mLoginPhone.getText().toString().trim();
        String varificationCode = mLoginCode.getText().toString().trim();
        String userName = loginUsername.getText().toString().trim();
        String password = loginPassword.getText().toString().trim();
        if (TextUtils.isEmpty(loginPhone) || TextUtils.isEmpty(varificationCode)) {
            mLoginButtonPhone.setEnabled(false);
        } else {
            mLoginButtonPhone.setEnabled(true);
        }
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            loginButton.setEnabled(false);
        } else {
            loginButton.setEnabled(true);
        }
    }

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (this.isShow == isShow) return;
        this.isShow = isShow;
        ObjectAnimator objectAnimator;
        if (isShow) {
            objectAnimator = ObjectAnimator.ofFloat(content, "translationY", new float[]{0, -translateDelta});
            setTitle(R.string.login_title);
        } else {
            objectAnimator = ObjectAnimator.ofFloat(content, "translationY", new float[]{-translateDelta, 0});
            setTitle("");
        }
        objectAnimator.setDuration(400);
        objectAnimator.start();
    }

    private class EditTextListner implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            changeLoginState();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private void switchContent(int index) {
        switch (index) {
            case 0:
                mPhoneContainer.setVisibility(View.VISIBLE);
                mPwdContainer.setVisibility(View.GONE);
                break;
            case 1:
                mPhoneContainer.setVisibility(View.GONE);
                mPwdContainer.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        int index = 0;
        switch (checkedId) {
            case R.id.rd_login_phone:
                index = 0;
                break;
            case R.id.rd_login_pwd:
                index = 1;
                break;
        }
        switchContent(index);
    }

    @Override
    public void showProgress(boolean show) {
        if (show) {
            mProgressDialog.show();
        } else {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void initProgressDialog() {
        mProgressDialog = new EBTProgressDialog(LoginActivity.this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    public void showTip(String tip) {
        ToastUtil.show(this, tip);
    }

    @Override
    public void updateVerificationCode(ValidateCodeSendResponse verificationCodeResult) {

        this.mVerificationCodeResult = verificationCodeResult;
    }

    /**
     * 开始倒计时计数
     */
    private void startTicking() {
        showProgress(true);
        if (mNormalTimerCounter == null) {
            mNormalTimerCounter = new TimerCounter(60 * 1000, 1000);
        } else {
            mNormalTimerCounter.cancel();
        }
        mNormalTimerCounter.start();
        StateManager.getInstance(this).setLong(StateManager.LOGIN_VALIDATECODE_TIME, System.currentTimeMillis());
    }

    private PlatformActionListener mLoginListener = new PlatformActionListener() {
        @Override
        public void onComplete(String thirtyType, HashMap<String, Object> userInfo) {
            mPresenter.thirtyPartLogin(userInfo.get(ShareConstants.PARAMS_USERID) + "", thirtyType, userInfo.get(ShareConstants.PARAMS_NICK_NAME) + ""
                    , userInfo.get(ShareConstants.PARAMS_IMAGEURL) + "");
        }

        @Override
        public void onError(String thirtyType, String error) {
            Toast.makeText(LoginActivity.this, error, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(String thirtyType) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mInitTimerCounter != null)
            mInitTimerCounter.cancel();
        if (mNormalTimerCounter != null)
            mNormalTimerCounter.cancel();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            if (qqLoginManager != null)
                qqLoginManager.onActivityResult(requestCode, resultCode, data);
            return;
        }
        mSsoHandler = WeiboLoginManger.getSsoHandler();
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    private void actionGetCode() {
        String phoneNo = mLoginPhone.getText().toString().trim();
        if (!TextUtils.isEmpty(phoneNo) && InputCheckUtil.phoneCheck(phoneNo)) {
            startTicking();
            mPresenter.sendVerificationCode(phoneNo);
        } else {
            showTip(getResources().getString(R.string.enter_correct_phone_number));
        }
    }

    @OnClick({R.id.login_button, R.id.action_wechat, R.id.action_weibo, R.id.action_qq, R.id.action_forget_pwd, R.id.login_button_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_button:
                final String userName = loginUsername.getText().toString().trim();
                final String userPwd = loginPassword.getText().toString().trim();
                mPresenter.login(userName, userPwd);
                TCAgent.onEvent(this, "click_login");
                break;
            case R.id.login_button_phone:
                String phone = mLoginPhone.getText().toString().trim();
                String verificationCode = mLoginCode.getText().toString().trim();
                if (TextUtils.isEmpty(verificationCode)) {
                    showTip(getResources().getString(R.string.enter_verification_code));
                    return;
                }
                if (mVerificationCodeResult == null || !mVerificationCodeResult.isSuccess) {
                    showTip(getResources().getString(R.string.get_verification_code_first));
                    return;
                }
                if (!phone.equals(mVerificationCodeResult.phone)) {
                    showTip(getResources().getString(R.string.enter_origin_phone_number));
                    return;
                }
                mPresenter.quickLogin(mVerificationCodeResult.getValidateId(), mVerificationCodeResult.phone, verificationCode);
                break;
            case R.id.action_forget_pwd:
                gotoActivity(ActForgetPwdGetAccount.class);
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_FORGET_PWD);
                break;
            case R.id.action_wechat:
                ILoginManager wechatManager = new WechatLoginManager(this);
                wechatManager.login(mLoginListener);
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_LOGIN_WECHAT);
                break;
            case R.id.action_weibo:
                ILoginManager weiboLogin = new WeiboLoginManger(this);
                weiboLogin.login(mLoginListener);
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_LOGIN_WEIBO);
                break;
            case R.id.action_qq:
                qqLoginManager = new QQLoginManager(this);
                qqLoginManager.login(mLoginListener);
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_LOGIN_QQ);
                break;
        }
    }

    private class TimerCounter extends CountDownTimer {

        public TimerCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mActionGetcode.setEnabled(false);
            mActionGetcode.setText(millisUntilFinished / 1000 + "S");
        }

        @Override
        public void onFinish() {
            mActionGetcode.setEnabled(true);
            mActionGetcode.setText(R.string.login_getcode_label);
        }
    }

}
